<?php

namespace Beerus\Modules\Wiki\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\wiki\Wiki as mWiki;
use Biz\service\wiki\AdmWiki;
use Doraemon\model\Member;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;

class ShareWikiListController extends Controller
{

    public function __construct()
    {
        parent::__construct();
    }

    public function index(Request $request, Content $content)
    {
        Admin::script($this->cancelShareScript());
        $requestParams = $request->all();
        $condition = $this->_index_condition($requestParams);

        $pageSize = $request->input("per_page", 10);
        $page = $request->input("page", 1);
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize
        ];

        $wikiList = AdmWiki::admShareWikiList($condition);
        $gridModel = new pGridDataModel($wikiList['list'], $wikiList['total'], [
            'perPage' => $pageSize
        ]);

        $query = $this->_filter_request($request);
        return $content
            ->header('分享的wiki商品列表')
            ->description(' ')
            ->row(
                Admin::grid($gridModel,
                    function (Grid $grid) use ($gridModel, $query, $condition, $request) {
                        $grid->paginate($gridModel->getPerPage());
                        $grid->filter(function ($filter) use ($query, $condition, $request) {

                            // 去掉默认的id过滤器
                            $filter->disableIdFilter();
                            $filter->column(1 / 2, function ($filter) {
                                // 在这里添加字段过滤器
                                $filter->dropDown('wiki_value', [
                                    'wiki_id' => '商品ID',
                                    'wiki_title' => '商品名称',
                                ]);

                                $filter->dropDown('user_value', [
                                    'uid' => '用户UID',
                                    'nick' => '用户昵称',
                                ]);

                            });
                            if (!empty($condition)) {
                                $filter->expand();//默认展开
                            }
                        });
                        $grid->disableExport();
                        $grid->disableCreateButton();
                        $grid->disableRowSelector();

                        $grid->column('id', '商品ID');
                        $grid->column('title', '商品名称')->width(200);

                        $grid->column('card_img', '首图')->width(200)->display(function () {
                            $imgPath = $this->cover_img;
                            $image = strlen($imgPath) ? "<img src='" . $imgPath . "' style='width:100px' class='img img-thumbnail' />" : "";
                            return $image;
                        });
                        $grid->column('recommendation', '推荐语')->width(100);
                        //$shareData=AdmWiki::getShareUsersTable($this->id);
                        $grid->column('share_count', '分享用户数')->popup('查看分享用户', function (){
                           // $data = AdmWiki::getShareUsersTable($this->id);
                            return new Table($this->share_table['header'], $this->share_table['list']);
                        })->width(100);

                        $grid->column('status_desc', '状态')->width(100);
                        $grid->column('category_desc', '商城类目')->width(150);
                        $grid->column('addtime', '创建时间')->width(100);

                        $grid->actions(function (Grid\Displayers\Actions $actions) use ($query) {
                            $actions->disableEdit();
                            $actions->disableDelete();
                            if ($actions->row->designer_share) {
                                $actions->prepend('<a class="fa fa-trash cancel-data" data-id="' . $actions->row->id . '" href="javascript:void(0);">取消设计师推荐</a>');
                            }
                            if ($actions->row->status != mWiki::STATUS_DEL) {
                                $actions->prepend('<a class="fa fa-edit" href="admList/' . $actions->row->id . '/edit?' . $query . '">编辑</a>');
                            }
                            $actions->prepend('<a class="fa fa-chain" href="javascript:layer.open({
                                type: 2,
                                title: \'第三方链接\',
                                maxmin: true,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $actions->row->url . '\'
                            });">链接</a>');
                            $actions->prepend('<a class="fa fa-envelope" href="javascript:layer.open({
                                type: 2,
                                title: \'预览\',
                                maxmin: true,
                                area: [\'800px\', \'500px\'],
                                content: \'' . $actions->row->h5_url . '\'
                            });">预览</a>');
                        });
                    }
                )
            );
    }

    private function getShareUsers()
    {
        $header = ['uid' => 'UID', 'name' => '用户昵称', 'type' => '用户身份'];
        $result['header'] = array_values($header);
        $result['list'] = [['uid' => 1, 'name' => 'tang', 'type' => '设计师']];
        return $result;
    }

    private function _filter_request(Request $request)
    {
        $params = $request->all();
        unset($params['_pjax']);
        return http_build_query($params);
    }

    public function _index_condition($request)
    {
        $response = [];

        //商品名称条件
        if (isset($request['wiki_title'])) {
            $wiki_value = trim($request['wiki_title']);
            if (strlen($wiki_value)) {
                $response['title[~]'] = $wiki_value;
            }
        }
        //wiki Id条件
        if (isset($request['wiki_id']) && ($request['wiki_id'] > 0)) {
            $response['id'] = $request['wiki_id'];
        }

        if (isset($request['uid']) && is_numeric($request['uid'])) {
            $response['uid'] = $request['uid'];
        }
        if (isset($request['nick'])) {
            $nick = trim($request['nick']);
            if (strlen($nick)) {
                $uid = Member::getUidByNick($nick);
                if($uid) {
                    $response['uid'] = $uid;
                }
            }
        }

        return $response;
    }

    public function cancel(Request $request, $id = 0)
    {
        try {
            $v = mWiki::getByWhere(['id' => $id]);
            if (!$v) {
                throw new \Exception('wiki信息不存在');
            }
            mWiki::update(['designer_share'=>0],['id'=>$id]);
            $success = [
                'title' => 'wiki ID: ' . $id . ' 已取消设计师推荐',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '修改失败,信息:' . $e->getFile() . $e->getLine() . $e->getMessage(),
                'code' => 0,
                'status' => false,
            ];
        }
        return response()->json($success);
    }


    private function cancelShareScript()
    {
        return <<<SCRIPT
        $('.cancel-data').unbind('click').click(function(){
            var id= $(this).data('id');
            if(confirm('确定要取消该wiki:'+id+'的设计师推荐吗？')){
                let url = 'shareWiki/' +  $(this).data('id')  + '/cancel'
                let params = {}
                $.post(url, params , function (result) {
                    if (result.code == 1) {
                        layer.msg(result.title);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 2000);
                    } else {
                        layer.msg(result.msg);
                    }
                });
            }
        });
SCRIPT;
    }
}
